<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-06-03
 * Time: 10:10
 */

namespace app\api\model\mp\v1;


use app\common\exception\ParameterException;
use app\common\exception\ResultException;
use app\common\model\BaseModel;
use think\facade\Validate;
use app\common\model\Content as ContentModel;

class Search
{
    /**
     * 获取搜索结果的分页数据
     * @param array $params
     * @return mixed
     */
    public static function getPaginationListData(array $params)
    {
        BaseModel::validatePaginationData($params);

        $validate = Validate::rule([
            'keyword' => 'require'
        ])->message([
            'keyword.require' => '关键词不能为空'
        ]);
        if (!$validate->check($params)) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        $likeText = '%' . $params['keyword'] . '%';

        // 定制搜索结果（模型表名如果修改了需要修改这里的代码）
        $caseTable = 'website_case wc';
        $informationTable = 'website_information wi';

        $contentModel = new ContentModel();
        $searchData = $contentModel->alias('c')
            ->join($caseTable,'c.table_id = wc.id AND c.model_id = 1', 'left')
            ->join($informationTable,'c.table_id = wi.id  AND c.model_id = 2', 'left')
            ->whereOr([
                ['c.title','like',$likeText],
                ['wc.keywords','like',$likeText],
                ['wi.keywords','like',$likeText],
                ['wc.desc','like',$likeText],
                ['wi.desc','like',$likeText]
            ])->field(['c.id','c.table_id','c.title','c.main_image','c.model_id'])
            ->paginate([
                'page' => $params['page'],
                'list_rows' => $params['limit']
            ],true);

        if ($searchData->isEmpty()) {
            throw new ResultException();
        }

        // 添加主图的域名前缀
        $searchData->visible(['id','model_id','title', 'main_image']);
//        $searchData->append(['prefix_main_image']);

        return $searchData;
    }
}